package com.example.myapplication;

import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.PowerManager;
import android.util.Log;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class UpdateService extends IntentService {
    public UpdateService() {
        super("UpdateService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        PowerManager.WakeLock wakeLock = pm.newWakeLock(
                PowerManager.PARTIAL_WAKE_LOCK,
                "MyApp::UpdateWakelock"
        );

        try {
            wakeLock.acquire(10 * 60 * 1000L /*10分钟*/);

            // 执行网络请求和数据库更新
            DBManager dbManager = new DBManager(this);
            List<RateItem> newData = fetchNetworkData();
            if (!newData.isEmpty()) {
                dbManager.addAll(newData);
                updateLastSyncTime();
            }

        } finally {
            if (wakeLock != null && wakeLock.isHeld()) {
                wakeLock.release();
            }
        }
    }

    private List<RateItem> fetchNetworkData() {
        List<RateItem> rateItems = new ArrayList<>();

        try {
            // 1. 发起网络请求（设置10秒超时）
            Document doc = Jsoup.connect("https://www.huilvbiao.com/bank/spdb")
                    .timeout(10 * 1000)
                    .get();

            // 2. 解析表格数据
            Element table = doc.selectFirst("table.table-bordered");
            if (table != null) {
                for (Element row : table.select("tbody tr")) {
                    processTableRow(row, rateItems);
                }
                Log.i("UpdateService", "成功解析到" + rateItems.size() + "条汇率数据");
            }
        } catch (IOException e) {
            Log.e("UpdateService", "网络请求失败: " + e.getMessage());
        } catch (Exception e) {
            Log.e("UpdateService", "数据解析异常: " + e.getMessage());
        }

        return rateItems;
    }

    private void processTableRow(Element row, List<RateItem> items) {
        try {
            Element currencyElem = row.selectFirst("th a.coin span");
            Element rateElem = row.selectFirst("td");

            if (currencyElem != null && rateElem != null) {
                // 3. 清理并转换汇率数值
                String currency = currencyElem.text().trim();
                String rateStr = rateElem.text().trim();
                double rate = parseRateValue(rateStr);

                items.add(new RateItem(0, currency, rate)); // ID由数据库自动生成
            }
        } catch (NumberFormatException e) {
            Log.e("RateParser", "无效的汇率格式: " + e.getMessage());
        }
    }

    private double parseRateValue(String rateStr) throws NumberFormatException {
        // 4. 移除所有非数字字符（保留小数点和数字）
        String cleanRate = rateStr.replaceAll("[^\\d.]", "");
        if (cleanRate.isEmpty()) {
            throw new NumberFormatException("空汇率值");
        }
        return Double.parseDouble(cleanRate);
    }

    private void updateLastSyncTime() {
        SharedPreferences sp = getSharedPreferences("rate_prefs", MODE_PRIVATE);
        String currentDate = new SimpleDateFormat("yyyyMMdd", Locale.getDefault())
                .format(new Date());
        sp.edit().putString("rate_date", currentDate).apply();
    }
}
